package  com.xyw.code.authorization.server.oauth2;

import com.xyw.code.authorization.common.entity.vo.SecurityUser;
import com.xyw.code.authorization.server.entity.User;
import com.xyw.code.authorization.server.feign.SysUserProvider;
import com.xyw.code.platform.common.entity.po.SysUser;
import io.netty.util.internal.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: xuyiwei
 * Date: 2020/2/10
 * Time: 下午1:12
 * Email: 1328312923@qq.com
 * Description: 自定义用户验证类
 **/
@Slf4j
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserProvider sysUserProvider;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<SysUser> sysUsers =  sysUserProvider.queryByUsername(username).getData();
        if (sysUsers==null ||sysUsers.size()==0) {
            log.debug("登录用户：" + username + " 不存在.");
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        User user = new User();
        BeanUtils.copyProperties(sysUsers.get(0),user);
        user.setEnabled(true);
        user.setAccountNonExpired(true);
        user.setCredentialsNonExpired(true);
        user.setAccountNonLocked(true);

        Set<GrantedAuthority> authorities = this.obtainGrantedAuthorities(user);
        return new SecurityUser(user.getId(), user.getUsername(), "{bcrypt}"+user.getPassword(), user.getDeptId() , authorities);
    }

    /**
     * 获得登录者所有角色的权限集合.
     *
     * @param user
     * @return
     */
    protected Set<GrantedAuthority> obtainGrantedAuthorities(User user) {
        String[] roles = {"Admin"};
        Set<String> staffsSet = new HashSet<>(Arrays.asList(roles));
        log.info("user:{},roles:{}", user.getUsername(), staffsSet);
        return staffsSet.stream().map(role -> new SimpleGrantedAuthority(role)).collect(Collectors.toSet());
    }
}
